package com.itheima.backend.controller;

import com.itheima.backend.pojo.User;
import com.itheima.backend.service.JIEKOU.UserService;
import com.itheima.backend.service.UserServiceImpl;
import com.itheima.backend.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.security.SignatureException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;


import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private UserServiceImpl userServiceImpl;


    // 登录接口，不需要令牌

    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody Map<String, String> loginData) {
        String username = loginData.get("username");
        String password = loginData.get("password");
        Map<String, Object> response = new HashMap<>();
        Integer id=userServiceImpl.getUserIdByUsername(username);
        if(id==null){
            response.put("message","用户不存在");
        }
        User user = userServiceImpl.login(username, password);


        if (user != null) {
            String token = JwtUtil.generateToken(username);
            response.put("message", "Login successful!");
            response.put("userId", user.getId());
            response.put("token", token); // 返回令牌
        } else {
            response.put("message", "Invalid username or password");
        }
        return response;
    }
//@PostMapping("/login")
//public Map<String, Object> login(@RequestBody Map<String, String> loginData) {
//    String username = loginData.get("username");
//    String password = loginData.get("password");
//
//    User user = userServiceImpl.login(username, password);
//
//    Map<String, Object> response = new HashMap<>();
//    if (user != null) {
//        // 生成令牌，包含 username 和 userId
//        String token = JwtUtil.generateToken(user.getId(), username);
//
//        response.put("message", "Login successful!");
//        response.put("userId", user.getId());
//        response.put("token", token); // 返回令牌
//    } else {
//        response.put("message", "Invalid username or password");
//    }
//    return response;
//}


    // 查询所有用户（需要登录）
    //应当开放给管理员权限

    @GetMapping
    public List<User> getAllUsers(HttpServletRequest request) {
        // 从过滤器中获取解析后的用户名
        String username = (String) request.getAttribute("username");
        System.out.println("Current user: " + username); // 可选：记录访问日志
        return userServiceImpl.getAllUsers();
    }

    // 根据 ID 查询用户（需要登录）
    @GetMapping("/{id}")

    public User getUserById(@PathVariable Integer id, HttpServletRequest request) {
        String username = (String) request.getAttribute("username");
        System.out.println("Current user: " + username);
        return userServiceImpl.getUserById(id);
    }

//    // 创建用户（需要登录）
//    //应该是注册用户
//    @PostMapping
//    public String createUser(@RequestBody User user, HttpServletRequest request) {
//        String username = (String) request.getAttribute("username");
//        System.out.println("Current user: " + username);
//        userServiceImpl.createUser(user);
//        return "User created successfully!";
//    }

    // 创建用户（需要登录）
    //应该是注册用户

    @PostMapping("/register")
    public Map<String, Object> createUser(@RequestBody Map<String, String> userData) {
        String username = userData.get("username");
        String password = userData.get("password");
        Map<String, Object> response = new HashMap<>();
        Integer id=userServiceImpl.getUserIdByUsername(username);
        if(id!=null){
            response.put("message","该用户已存在");
        }
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        userServiceImpl.createUser(user);
        response.put("message","创建成功咯");
        return response;
    }

    // 删除用户（需要登录）
    //留给管理员

    @DeleteMapping("/{id}")
    public String deleteUser(@PathVariable Integer id, HttpServletRequest request) {
        String username = (String) request.getAttribute("username");
        System.out.println("Current user: " + username);
        if(username != null && username.equals("nagisa")){
            userServiceImpl.deleteUserById(id);
            return "User deleted successfully!";
        }
        else{
            return "你不被允许删除用户或者该用户并不存在";
        }

    }


    @PostMapping("/validate")
    public ResponseEntity<?> validateToken(@RequestHeader("Authorization") String token) {
        try {
            // 移除 Bearer 前缀
            if (token == null || !token.startsWith("Bearer ")) {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                        .body(Map.of("message", "Invalid token format!"));
            }
            token = token.substring(7); // 移除前缀

            // 验证并解析 JWT
            Claims claims = JwtUtil.validateToken(token);

            // 提取用户名
            String username = claims.getSubject();

            return ResponseEntity.ok(Map.of(
                    "message", "Token is valid",
                    "username", username
            ));
        } catch (ExpiredJwtException e) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                    .body(Map.of("message", "Token has expired: " + e.getMessage()));
        } catch (MalformedJwtException e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body(Map.of("message", "Invalid token format: " + e.getMessage()));
        } catch (SignatureException e) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                    .body(Map.of("message", "Invalid token signature: " + e.getMessage()));
        } catch (IllegalArgumentException e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                    .body(Map.of("message", "Token is missing or malformed: " + e.getMessage()));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Map.of("message", "Error validating token: " + e.getMessage()));
        }
    }




}
